package com.yaoxun.console.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import com.yaoxun.console.code.BaseResponseCode;
import com.yaoxun.console.context.SubjectContextHolder;
import com.yaoxun.console.service.JsonService;
import com.yaoxun.console.service.LoginService;
import com.yaoxun.console.xo.dto.LoginSession;
import com.yaoxun.console.xo.resp.ApiResp;

public class SecurityInterceptor implements AsyncHandlerInterceptor, InitializingBean {

	@Autowired
	private LoginService loginService;
	
	@Autowired
	private JsonService jsonService;
	
	private String noAuthJson = "";
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		LoginSession session = loginService.getSession(request);
		
		if(session == null) {
			this.handleNoAuth(request, response);
			return false;			
		}
		
		loginService.refreshSession(response, session);
		
		SubjectContextHolder.setContext(session);
		
		return true;
		
	}

	private boolean isJsonReq(HttpServletRequest request) {
		
		String contentType = request.getContentType();
		
		if(StringUtils.isBlank(contentType)) {
			return false;
		}
		
		if("application/json".equals(contentType) 
				|| "application/json;utf-8".equals(contentType)) {
			return true;
		}
		
		return false;
	}
	
	private void handleNoAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		boolean flag = isJsonReq(request);
		
		if(flag) {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json;utf-8");
			response.getWriter().println(noAuthJson);
			return ;
		}
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		SubjectContextHolder.clearContext();
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		noAuthJson = jsonService.toJsonString(ApiResp.of(BaseResponseCode.NOT_AUTH));
	}

	
	
	
}
